//
//  SINATecScoreQueryDetailViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/8.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINATecScoreQueryDetailViewController.h"
#import "SINACircularBeadUtils.h"
#import "SINATecScoreQuerDetailItemViewController.h"
#import "SINAUiviewClickLiserner.h"
#import "SINACustomModelPickView.h"
#import "SINAStuSchoolYearModel.h"
@interface SINATecScoreQueryDetailViewController ()<UIScrollViewDelegate,CustomModelPickViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollView;
@property (weak, nonatomic) IBOutlet UIView *mainContentView;
@property (weak, nonatomic) IBOutlet UIView *mainTitleView;
@property (weak, nonatomic) IBOutlet UIView *mainSelectClassView;
@property (weak, nonatomic) IBOutlet UIView *mainOtherView;

//分栏下的分隔线
@property (weak, nonatomic) IBOutlet UIView *otherDiviView;

@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
@property (weak, nonatomic) IBOutlet UIImageView *userTitleImageView;
//学生成绩详情
@property (weak, nonatomic) IBOutlet UILabel *scoreDetaileLabel;
//个人综合测评
@property (weak, nonatomic) IBOutlet UILabel *personalComprehensiveEvaluationLabel;
//指示线
@property (weak, nonatomic) IBOutlet UIView *diviView;
@property(strong,nonatomic) NSArray *topDataList;
@property(strong,nonatomic) NSMutableArray *schoolYearDataList;


@property (weak, nonatomic) IBOutlet UILabel *studentNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *studentSchoolClass;
@property (weak, nonatomic) IBOutlet UIImageView *studentTitleimageView;

@property (weak, nonatomic) IBOutlet UILabel *schoolYearTitleLabel;


@property(strong,nonatomic) SINATecScoreQuerDetailItemViewController *studentScoreListController;

@property(strong,nonatomic) SINAStuSchoolYearModel *currentSchoolYearModel;
@end

@implementation SINATecScoreQueryDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"成绩详情";
    self.schoolYearDataList =[[NSMutableArray alloc]init];
    [SINACircularBeadUtils makeCircularView:self.userTitleImageView];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.scoreDetaileLabel andWithBlick:^(UIView *view) {
        [self selectPage:0];
        
    }];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.personalComprehensiveEvaluationLabel andWithBlick:^(UIView *view) {
        [self selectPage:1];
    }];
    
    self.mainScrollView.frame=CGRectMake(0, 0, mainW, mainH);
    self.mainContentView.frame=CGRectMake(0, 0, mainW, mainH);
    self.mainTitleView.frame=CGRectMake(0, 0, mainW, 100);
    self.mainSelectClassView.frame=CGRectMake(0, CGRectGetMaxY(self.mainTitleView.frame)+15, mainW, 48);
    self.mainOtherView.frame=CGRectMake(0, CGRectGetMaxY(self.mainSelectClassView.frame)+15, mainW, 48);
    self.otherDiviView.frame=CGRectMake(0, CGRectGetMaxY(self.mainOtherView.frame)-1, mainW, 1);
    self.contentScrollView.frame=CGRectMake(0, CGRectGetMaxY(self.mainOtherView.frame)+1, mainW, mainH-CGRectGetMaxY(self.mainOtherView.frame)+50);
    self.mainScrollView.contentSize=CGSizeMake(mainW, mainH+115);
    self.mainScrollView.scrollEnabled=YES;
    self.contentScrollView.scrollEnabled=YES;
    
    
    self.contentScrollView.tag=101;
    self.mainScrollView.tag=102;
    self.mainScrollView.delegate=self;
    
    [self initOtherController];
    [super initBackItem];
    
    [self loadingUserInformationFunction];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.mainSelectClassView andWithBlick:^(UIView *view) {
        [self showSelectSchoolYearFunction];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    if(recognizer.direction == UISwipeGestureRecognizerDirectionDown) {
        DLog(@"swipe down");
    }
    if(recognizer.direction == UISwipeGestureRecognizerDirectionUp) {
        DLog(@"swipe up");
    }
    if(recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        DLog(@"swipe left");
    }
    if(recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        DLog(@"swipe right");
    }
}


-(void)selectPage:(NSInteger)index{
    if (index==0) {
        
        
        self.scoreDetaileLabel.textColor=baseSelectColor;
        self.personalComprehensiveEvaluationLabel.textColor=[UIColor colorWithHexString:@"#212121"];
        CGPoint point = CGPointMake(0, self.contentScrollView.contentOffset.y);
        [self.contentScrollView setContentOffset:point animated:YES];
        //时长，延时，弹性（越小弹性越大），初始速度
        [UIView animateWithDuration: 0.9 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.3 options:0 animations:^{
            self.diviView.centerX=self.scoreDetaileLabel.centerX;
        } completion:nil];
        
    } else {
        self.personalComprehensiveEvaluationLabel.textColor=baseSelectColor;
        self.scoreDetaileLabel.textColor=[UIColor colorWithHexString:@"#212121"];
        CGPoint point = CGPointMake(1*mainW, self.contentScrollView.contentOffset.y);
        [self.contentScrollView setContentOffset:point animated:YES];
        //时长，延时，弹性（越小弹性越大），初始速度
        [UIView animateWithDuration: 0.9 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.3 options:0 animations:^{
            self.diviView.centerX=self.personalComprehensiveEvaluationLabel.centerX;
        } completion:nil];
        
    }
}

-(NSArray *)topDataList{
    if (!_topDataList) {
        _topDataList= @[@"课程",@"姓名"];
    }
    return _topDataList;
}
-(void)initOtherController{
    NSArray *array = @[@"SINATecScoreQuerDetailItemViewController",@"SINATecScoreQuerDetailEvaluationItemViewController"];
    for (NSInteger i=0; i<array.count; i++) {
        //取出数据
        NSString *item = array[i];
        //创建
        UIViewController *controller = [[NSClassFromString(item) alloc] init];
        if(i==0){
            ((SINATecScoreQuerDetailItemViewController*)controller).prentScrollView=self.mainScrollView;
        }
        //设置标题
        //controller.title = self.topDataList[i];
        
        [self addChildViewController:controller];
    }
    //将子控制器的View添加到MainView的scrollView中
    //4 设置scrollview的contentsize
    self.contentScrollView.contentSize=CGSizeMake([UIScreen mainScreen].bounds.size.width*self.topDataList.count, 0);
    //5 设置uiscrollView的代理
    self.contentScrollView.delegate=self;
    self.contentScrollView.pagingEnabled=YES;
    //进入主控制器的第一个页面
    [self scrollViewDidEndDecelerating:self.contentScrollView];
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    if (scrollView.tag==102) {
        return;
    }
    //每一个子控制器的宽度
    CGFloat width =scrollView.frame.size.width;
    //每一个子控制器的高度
    CGFloat height =CGRectGetHeight(self.contentScrollView.frame);
    //获取当前索引值
    NSInteger idx = scrollView.contentOffset.x/width;
    
    //设置联动
    [self selectPage:idx];
    //[self.topBarView scrollChangTopBar:idx];
    //根据索引值返回引用
    UIViewController *vc=self.childViewControllers[idx];
    //判断当前的vc是否执行过viewLoaded
    if([vc isViewLoaded]){
        return;
    }else{
        //设置子控制器的视图大小
        vc.view.frame=CGRectMake(scrollView.contentOffset.x, 0, scrollView.frame.size.width, height);
        //将子控制器的view加入到scrollview中
        [scrollView addSubview:vc.view];
        
        if ([vc isKindOfClass:[SINATecScoreQuerDetailItemViewController class]]) {
            self.studentScoreListController=(SINATecScoreQuerDetailItemViewController*)vc;
        }
    }
}
//滑动减速结束
//调用加载子控制器的view的方法
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    //DLog(@"滑动结束 ...");
    [self scrollViewDidEndScrollingAnimation:scrollView];
}
//scrollView滚动时，就调用该方法。任何offset值改变都调用该方法。即滚动过程中，调用多次

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //DLog(@"scrollViewDidScroll");
    
    CGPoint point=scrollView.contentOffset;
    
    DLog(@"%f,%f",point.x,point.y);
    
    if (point.y>115) {
        self.mainScrollView.scrollEnabled=NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noti1" object:nil];
    }else if (point.y==115){
        self.mainScrollView.scrollEnabled=YES;
    }else if (point.y==0){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noti1" object:nil];
    }
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



//获取用户个人信息详情
-(void) loadingUserInformationFunction{
    NSString *userUid=self.model.uuid;
    DLog(@"获取用户个人信息详情 uid is %@",userUid);
    if (userUid==nil||userUid.length<1) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"用户信息异常，请重新登录" sureBtn:@"确定" cancleBtn:nil];
        [alertView showXLAlertView];
    } else {

        [self startLoading];
        WeakSelf;
        [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@?uuid=%@",baseUrl,userInformationUrl,userUid]  success:^(id responseData) {
            NSString *code = responseData[@"code"];
            NSString *universityname=@"无";
            NSString *realname=@"无";
            NSString *collname=@"无";
            NSString *classifyname=@"无";
            NSString *headimg=@"";
            [weakSelf stopLoading];
            if ([code isEqualToString:@"1000"]) {
                NSDictionary *personInfromation = responseData[@"content"];
                universityname=personInfromation[@"universityname"];
                realname=personInfromation[@"realname"];
                collname=personInfromation[@"collname"];
                classifyname=personInfromation[@"classifyname"];
                headimg = personInfromation[@"headimg"];
                
            }else if ([code isEqualToString:@"1003"]) {
                WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"验证失败" sureBtn:@"确定" cancleBtn:nil];
                [alertView showXLAlertView];
                
                universityname=@"加载失败";
                realname=@"加载失败";
                collname=@"加载失败";
                classifyname=@"加载失败";
            }else{
                NSString *message =responseData[@"message"];
                WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
                [alertView showXLAlertView];
                universityname=@"加载失败";
                realname=@"加载失败";
                collname=@"加载失败";
                classifyname=@"加载失败";
            }
            
            weakSelf.studentNameLabel.text=realname;
            weakSelf.studentSchoolClass.text=universityname;
            [weakSelf.studentTitleimageView sd_setImageWithURL:[NSURL URLWithString:headimg]];
            [weakSelf loadingSchoolYearListNetData];
        } failure:^(NSError *error, NSInteger errCode) {
            [weakSelf stopLoading];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"网络异常 稍后重试" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
            
            NSString *universityname=@"无";
            NSString *realname=@"无";
            NSString *collname=@"无";
            NSString *classifyname=@"无";
            
            universityname=@"加载失败";
            realname=@"加载失败";
            collname=@"加载失败";
            classifyname=@"加载失败";
            
            weakSelf.studentNameLabel.text=realname;
            weakSelf.studentSchoolClass.text=universityname;
            
            [weakSelf loadingSchoolYearListNetData];
        }];
    }
}

//获取学年信息
-(void)loadingSchoolYearListNetData{

    DLog(@"学生成绩页面 获取学年信息");
    
    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //用户的uuid String uuid
    
    [dict setObject:self.model.uuid forKey:@"uuid"];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,stuGetSchoolYearListUrl] withParamters:dict success:^(id responseData) {
        [weakSelf stopLoading];
        NSString *code = responseData[@"code"];
        
        if ([code isEqualToString:@"1000"]) {
            NSArray *result = responseData[@"content"];
            if (result==nil||result.count==0) {
                self.schoolYearTitleLabel.text=@"暂无学年信息";
            } else {
                //有学年信息
                for(NSInteger i=0;i<result.count;i++){
                    NSDictionary *dic = result[i];
                    SINAStuSchoolYearModel *model = [[SINAStuSchoolYearModel alloc] initWithDict:dic];
                    SINACommonPopModel *popModel = [[SINACommonPopModel alloc]init];
                    popModel.model=model;
                    popModel.title=[NSString stringWithFormat:@"%@ %@",model.schoolyear,model.term];
                    if (i==0) {
                        self.schoolYearTitleLabel.text=[NSString stringWithFormat:@"%@ %@",model.schoolyear,model.term];
                        self.currentSchoolYearModel = model;
                        if (self.studentScoreListController!=nil) {
                            DLog(@"学生成绩页面 获取学年信息 成功 加载成绩详情");
                            [self.studentScoreListController loadingStudentScoreList:self.currentSchoolYearModel andWithUser:self.model];
                        }
                    }
                    [self.schoolYearDataList addObject:popModel];
                }
                
            }
        }else{
            self.schoolYearTitleLabel.text=@"暂无学年信息";
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
            
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        self.schoolYearTitleLabel.text=@"暂无学年信息";
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        
    }];
}


-(void) showSelectSchoolYearFunction{
    
    
    if (self.schoolYearDataList.count==0) {
        [self loadingSchoolYearListNetData];
        return;
    }
    
    SINACustomModelPickView *pickerSingle = [[SINACustomModelPickView alloc]init];
    
    [pickerSingle setDataArray:self.schoolYearDataList];
    [pickerSingle setDefalutSelectRowStr:0];
    pickerSingle.titleLabel.text=@"选择学年";
    pickerSingle.tag=100;
    
    [pickerSingle setDelegate:self];
    
    [pickerSingle show];
    [self.view endEditing:YES];
}

#pragma mark - CustomModelPickViewDelegate method
-(void)customModelPickView:(SINACustomModelPickView *)customPickView selectedTitle:(SINACommonPopModel *)selectedModel{
    self.currentSchoolYearModel = (SINAStuSchoolYearModel*)selectedModel.model;;
    self.schoolYearTitleLabel.text = selectedModel.title;
    
    if (self.studentScoreListController!=nil) {
        [self.studentScoreListController loadingStudentScoreList:self.currentSchoolYearModel andWithUser:self.model];
    }
}

-(void)dismissCustomPickView:(SINACustomModelPickView *)customPickView{
    
}

#pragma mark -   BasePickViewDelegate
- (void)dismissBasePickView:(SINABasePickView *)customPickView
{
    
}


@end
